import ora from 'ora'
import download from './core/download'
import { extract, rewritePackage } from './core/file'
import install from './core/install'

export default async (targetPath: string, downloadUrl: string | URL): Promise<void> => {
  const spinner = ora('Downloading template...').start()

  try {
    // 将文件下载到临时目录
    const tempPath = await download(downloadUrl as string)
    // 将文件解压到指定位置
    await extract(tempPath, targetPath, 1)
    // 如果模板存在package.json，重写项目名称
    const packagePath = await rewritePackage(targetPath)
    spinner.succeed('Download template complete.')

    if (packagePath !== '') {
      await install(targetPath)
    }
  } catch (error) {
    spinner.fail((error as Error).message)
  }
}
